package com.videostreaming.controller.base;

import com.gooddies.wiring.annotations.Wire;
import com.videostreaming.db.DBImpl;
import com.videostreaming.db.DB;
import com.wiringweb.annotations.ExceptionHandler;
import com.wiringweb.annotations.PostRequest;
import com.wiringweb.annotations.PreRequest;
import com.wiringweb.exceptions.ExceptionSettings;
import com.wiringweb.resolution.Resolution;
import com.wiringweb.servlet.BaseWiringWebController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

/**
 * @author sad
 */
public abstract class BaseDbController extends BaseWiringWebController {
    
    public final String LOGGED_USER="loggedUser";
    
    @Wire
    private DBImpl db;
    private SqlSession session;

    protected SqlSession getDBSession() {
        return session;
    }

    protected DB getDb() {
        return session.getMapper(DB.class);
    }

    @PreRequest
    private void startSession(HttpServletRequest request) {
        addRequestParameter("cp", request.getContextPath());
        addRequestParameter("cpWithoutSlash", request.getContextPath().substring(1));
        session = db.openSession();
    }

    @PostRequest
    private void closeSession(HttpServletRequest request, Resolution response) {
        session.commit();
        session.close();
    }

    @ExceptionHandler
    private void rollbackSession(Throwable thr, HttpServletRequest request, HttpServletResponse response, ExceptionSettings settings) {
        session.rollback();
        session.close();
    }
}
